package com.artifact.mit.mypoint.http;

import java.io.UnsupportedEncodingException;
import java.util.List;

import org.apache.http.Header;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.client.methods.HttpRequestBase;
import org.apache.http.impl.client.DefaultHttpClient;

import android.util.Log;

public class MyPointHttpClient implements MyPointHttpMethod {

	private final HttpClient httpClient;

	private HttpPost httpPost;
	private HttpGet httpGet;

	public MyPointHttpClient() {
		httpClient = new DefaultHttpClient();
	}

	public HttpResponse post(String uri, Header[] headers) {
		httpPost = new HttpPost(uri);
		httpPost.setHeaders(headers);
		return executeRequest(httpPost);
	}
	
	public HttpResponse post(String uri, Header[] headers, List<NameValuePair> parameters) {
		httpPost = new HttpPost(uri);
		httpPost.setHeaders(headers);
		try {
			httpPost.setEntity(new UrlEncodedFormEntity(parameters));
			return executeRequest(httpPost);
		} catch (UnsupportedEncodingException e) {
			Log.e(this.getClass().getName(), "Http Post Error", e);
		}
		return null;
	}

	public HttpResponse get(String uri, Header[] headers) {
		httpGet = new HttpGet(uri);
		httpGet.setHeaders(headers);
		return executeRequest(httpGet);
	}
	
	private HttpResponse executeRequest(HttpRequestBase request) {
		try {
			return httpClient.execute(request);
		} catch (Exception e) {
			Log.e(this.getClass().getName(), "Http Response Error", e);
		}
		return null;
	}
}